package com.gx.smart.building.ui.common.activity;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.czt.mp3recorder.MP3Recorder;
import com.gx.smart.base.BaseViewModel;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: xiaosy
 * 时间: 2022/6/17
 * @Description: 上传音频文件和图片以及播放音频
 * @Version: 1.0
 **/
public abstract class BaseMVVMActivityUploadFileV4<VM extends BaseViewModel> extends BaseMVVMActivityUploadFileV3<VM> implements Handler.Callback {
    protected com.shuyu.waveview.AudioPlayer audioPlayer;
    protected Handler mRemoteHandler;
    protected MP3Recorder mRecorder;
    protected String filePath;
    protected boolean mIsRecord = false;
    protected boolean mIsPlay = false;

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case AudioPlayer.HANDLER_COMPLETE:
                playComplete();
                break;
            case AudioPlayer.HANDLER_ERROR:
                ToastUtils.showLong("播放发生错误");
                if (audioPlayer != null) {
                    audioPlayer.pause();
                }
                break;
        }
        return false;
    }

    protected abstract void playComplete();

    protected void initAudioPlayer() {
        mRemoteHandler = new Handler(this);
        audioPlayer = new AudioPlayer(this, mRemoteHandler);
    }

    /**
     * 开始录音
     */
    public void startRecord() {
        filePath = Utils.getApp().getExternalCacheDir() + File.separator + UUID.randomUUID().toString() + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));
        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    ToastUtils.showLong("没有麦克风权限");
                    recordError();
                }
            }
        });

        try {
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtils.showLong("录音出现异常");
            recordError();
            return;
        }
        mIsRecord = true;
    }

    /**
     * 录音异常
     */
    public void recordError() {
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    /**
     * 停止录音
     */
    public void stopRecord() {
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
        }
        mIsRecord = false;
    }

    public void uploadAudio() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            ToastUtils.showLong("文件不存在");
            return;
        }
        new UploadAudioAsyncTask().execute(filePath);
    }

    protected abstract void uploadAudio(String fileName, byte[] file, long duration);

    /**
     * 播放
     */
    public void audioPlay() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            ToastUtils.showLong("文件不存在");
            return;
        }
        mIsPlay = true;
        if (audioPlayer != null) {
            audioPlayer.playUrl(filePath);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        audioPlayRelease();
        if (mIsRecord) {
            stopRecord();
        }
        mIsPlay = false;
    }

    /**
     * 暂停
     */
    public void audioPlayPause() {
        if (mIsPlay) {
            if (audioPlayer != null) {
                audioPlayer.pause();
            }
        }
    }

    public void audioPlayRelease() {
        if (mIsPlay) {
            if (audioPlayer != null) {
                audioPlayer.pause();
                audioPlayer.stop();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mRemoteHandler != null) {
            mRemoteHandler.removeCallbacksAndMessages(null);
        }
    }

    class UploadAudioAsyncTask extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            byte[] file = FileIOUtils.readFile2BytesByStream(filePath);
            String fileName = com.blankj.utilcode.util.FileUtils.getFileName(filePath);
            long duration = audioPlayer.getDurationLocation(Utils.getApp(), filePath);
            uploadAudio(fileName, file, duration);
            return null;
        }

    }
}
